﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SASystem.SAServiceRef;

namespace SASystem
{
    public partial class CacheMgrFrm : Form
    {
        private bool m_cancel;

        public CacheMgrFrm()
        {
            InitializeComponent();
        }

        private void CacheMgrFrm_Load(object sender, EventArgs e)
        {
            SABLL.InitCacheTreeView(this.treeView_Cache);

            //SABLL.GetService().RaiseStartCachingEvent += new SAServices.PubService.StartCachingEventHandler(GetService()_RaiseStartCachingEvent);
            //SABLL.GetService().RaiseEndCachingEvent += new SAServices.PubService.EndCachingEventHandler(GetService()_RaiseEndCachingEvent);
            //SABLL.GetService().RaiseCacheStepEvent += new SAServices.PubService.CacheStepEventHandler(GetService()_RaiseCacheStepEvent);

            m_cancel = false;
        }

        private void button_CreateCache_Click(object sender, EventArgs e)
        {
            DoCreateCache();
        }

        //void GetService()_RaiseCacheStepEvent(object sender, SAServices.ProgressEventArgs e)
        //{
        //    this.progressBar1.PerformStep();
        //}

        //void GetService()_RaiseEndCachingEvent(object sender, SAServices.ProgressEventArgs e)
        //{
        //    this.progressBar1.Value = 1;
        //}

        //void GetService()_RaiseStartCachingEvent(object sender, SAServices.ProgressEventArgs e)
        //{
        //    this.progressBar1.Step = 1;
        //    this.progressBar1.Minimum = 1;
        //    this.progressBar1.Maximum = e.Step;
        //    this.progressBar1.Value = 1;

        //    Application.DoEvents();
        //}

        private void DoCreateCache()
        {
            m_cancel = false;
            this.Cursor = Cursors.WaitCursor;
            List<FamilyInfo> familyList = GetFamiliesBySelectedNodes();

            int totalCnt = familyList.Count;
            int curIdx = 1;

            int successCnt = 0;
            foreach (FamilyInfo item in familyList)
            {
                if (m_cancel) break;
                
                this.label_Msg.Text = String.Format("正在缓存{0}({1}/{2})...", item.Name, curIdx++, totalCnt);
                Application.DoEvents();
                if (!item.IsCached)
                {
                    //do cache.
                    bool success = SABLL.GenerateCache(item.ID);
                    if (success) successCnt++;
                }
            }

            this.Cursor = Cursors.Default;

            this.label_Msg.Text = String.Format("生成缓存成功！零件数目：{0}",successCnt);
            RefreshCacheTreeView(this.treeView_Cache);
        }

        private void button_DeleteCache_Click(object sender, EventArgs e)
        {
            m_cancel = false;
            this.Cursor = Cursors.WaitCursor;

            List<FamilyInfo> familyList = GetFamiliesBySelectedNodes();

            int totalCnt = familyList.Count;
            int curIdx = 1;

            int successCnt = 0;
            foreach (FamilyInfo item in familyList)
            {
                this.label_Msg.Text = String.Format("正在删除{0}({1}/{2})...", item.Name, curIdx++, totalCnt);
                Application.DoEvents();

                if (true)
                {
                    //delete cache.
                   bool success = SABLL.DeleteCache(item.ID);

                   if (!success)
                   {
                       SABLL.DoAlert();
                   }
                   else
                   {
                       successCnt++;
                   }
                }
            }

            this.Cursor = Cursors.Default;
            this.label_Msg.Text = String.Format("删除缓存成功！零件总数：{0}", successCnt);
            RefreshCacheTreeView(this.treeView_Cache);
        }

        internal void RefreshCacheTreeView(System.Windows.Forms.TreeView treeView)
        {
            TreeNodeCollection nodes = this.treeView_Cache.Nodes;

            foreach (TreeNode node in nodes)
            {
                RefreshSelectedNode(node);
            }
        }


        private void RefreshSelectedNode(TreeNode node)
        {
            if (node == null)
            {
                return;
            }
            
            if (node.Checked)
            {
                FamilyInfo famInfo = node.Tag as FamilyInfo;

                if (famInfo != null)
                {
                    famInfo.IsCached = SABLL.IsFamilyCached(famInfo.ID);
                    if (famInfo.IsCached)
                    {
                        //cached.
                        node.ImageIndex = (int)CacheNodeImgList.kCached;
                    }
                    else
                    {
                        //not cached.
                        node.ImageIndex = (int)CacheNodeImgList.kNotCached;
                    }
                }
            }

            foreach (TreeNode subNode in node.Nodes)
            {
                RefreshSelectedNode(subNode);
            }

            return;
        }


        private List<FamilyInfo> GetFamiliesBySelectedNodes()
        {
            List<FamilyInfo> retInfo = new List<FamilyInfo>();

            TreeNodeCollection nodes = this.treeView_Cache.Nodes;

            foreach (TreeNode node in nodes)
            {
                AddIfSelectedFamilyNode(node, retInfo);
            }

            return retInfo;
        }

        private void AddIfSelectedFamilyNode(TreeNode node, List<FamilyInfo> retInfo)
        {
            if (retInfo == null || node == null)
            {
                return;
            }

            if (node.Checked)
            {
                FamilyInfo famInfo = node.Tag as FamilyInfo;

                if (famInfo != null)
                {
                    //now add the family.
                    retInfo.Add(famInfo);
                }
            }

            foreach (TreeNode subNode in node.Nodes)
            {
                AddIfSelectedFamilyNode(subNode, retInfo);
            }

            return;
        }

        private void button_Cancel_Click(object sender, EventArgs e)
        {
            m_cancel = true;
        }

        private void button_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void treeView_Cache_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (e.Action != TreeViewAction.Unknown)
            {
                SetNodeCheckStatus(e.Node, e.Node.Checked); 
            }
        }

       private void SetNodeCheckStatus(TreeNode tn, bool Checked)
        {
           
          if (tn == null) return;  
          foreach (TreeNode tnChild in tn.Nodes)  
          {  
  
              tnChild.Checked = Checked;  
  
              SetNodeCheckStatus(tnChild, Checked);  
            }
          TreeNode tnParent = tn;  
      }

       private void treeView_Cache_AfterSelect(object sender, TreeViewEventArgs e)
       {
           if (e.Node != null)
           {
               if ((e.Node.Tag as CategoryInfo) != null)
               {
                   e.Node.SelectedImageIndex = (int)CacheNodeImgList.kFolder;
               }
               else
               {
                   FamilyInfo famInfo = e.Node.Tag as FamilyInfo;
                   if (famInfo != null)
                   {
                       if (famInfo.IsCached)
                       {
                           e.Node.SelectedImageIndex = (int)CacheNodeImgList.kCached;
                       }
                       else
                       {
                           e.Node.SelectedImageIndex = (int)CacheNodeImgList.kNotCached;
                       }
                   }
               }
           }
       }  
    }
}
